package cn.lisens.serial.service;

import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;

import com.fazecast.jSerialComm.SerialPort;

@Service
public class CM850Service {
	private SerialPort serialPort;

    // 初始化串口
    public void initSerialPort(String portName) throws Exception {
        serialPort = SerialPort.getCommPort(portName);
        serialPort.setBaudRate(115200);
        serialPort.setComPortParameters(115200, 8, 1, SerialPort.NO_PARITY);
        
        if (!serialPort.openPort()) {
            throw new Exception("Failed to open port: " + portName);
        }
    }

    // 发送AT指令并返回响应
    public String sendATCommand(String command, int timeoutMs) throws Exception {
        serialPort.writeBytes((command + "\r\n").getBytes(), command.length() + 2);
        Thread.sleep(timeoutMs);
        
        byte[] buffer = new byte[serialPort.bytesAvailable()];
        int read = serialPort.readBytes(buffer, buffer.length);
        return new String(buffer, 0, read);
    }

    // 发送短信
    public String sendSMS(String phoneNumber, String message) throws Exception {
        // 1. 设置文本模式
        sendATCommand("AT+CMGF=1", 500);
        
        // 2. 发送号码和内容（以Ctrl+Z结尾）
        String cmd = "AT+CMGS=\"" + phoneNumber + "\"";
        String response = sendATCommand(cmd, 500);
        
        if (response.contains(">")) {
            serialPort.writeBytes((message + "\u001A").getBytes(), message.length() + 1);
            Thread.sleep(1000); // 等待响应
            byte[] buffer = new byte[serialPort.bytesAvailable()];
            serialPort.readBytes(buffer, buffer.length);
            return new String(buffer);
        } else {
            throw new Exception("Failed to send SMS: " + response);
        }
    }

    @PreDestroy
    public void closePort() {
        if (serialPort != null && serialPort.isOpen()) {
            serialPort.closePort();
        }
    }
}
